package com.zt.student.service.impl;

import com.zt.common.common.ApiException;
import com.zt.common.common.CodeMsg;
import com.zt.common.pojo.exam.Exam;
import com.zt.common.utils.JwtUtil;
import com.zt.student.dao.ExamDao;
import com.zt.student.dto.ExamAnswerDTO;
import com.zt.student.service.ClassSelectionService;
import com.zt.student.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.List;

/**
 * description:
 * author:zt
 * date:2022-02-15
 */
@Service
@Transactional
public class ExamServiceImpl implements ExamService {

    @Autowired
    private ExamDao examDao;
    @Autowired
    private ClassSelectionService classSelectionService;

    @Override
    public List<Exam> getExamByClassId(HttpServletRequest request, int classId) {
        if (classSelectionService.getByStuIdAndClassId(request,classId)==null)
            throw new ApiException(CodeMsg.CLASS_NOT_BELONG);

        return examDao.getExamByClassId(classId);
    }

    @Override
    public List<ExamAnswerDTO> getQuestionAndAnswer(HttpServletRequest request, int examId) {
        String studentId = JwtUtil.decodedGetID(request.getHeader("Authorization"));
//        String studentId = "20181003126";

        List<ExamAnswerDTO> questionAndAnswer = examDao.getQuestionAndAnswer(examId, studentId);
        //获取该班级所有学生数量
        int classStuNumber = examDao.getClassStuNumber(examId);

        DecimalFormat decimalFormat = new DecimalFormat("0.0000");
        for (ExamAnswerDTO q : questionAndAnswer) {
            //获取本次考试该题目的所有回答
            List<String> totalAnswers = examDao.getAnswerByQuestionId(examId, q.getQuestionId());
            //没有回答
            if (totalAnswers.size() == 0) {
                q.setCorrectRate("0.0000");
                continue;
            }
            //获取该题目所有回答中正确的数量
            double correctNumber = totalAnswers.stream().filter(a -> a.equals(q.getStandardAnswer())).count();

            String rate = decimalFormat.format(correctNumber / classStuNumber);
            q.setCorrectRate(rate);
        }
        return questionAndAnswer;
    }
}
